package com.yz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yz.common.CustomException;
import com.yz.entity.*;
import com.yz.mapper.OrdersMapper;
import com.yz.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 提交订单
     * @param order
     * @param session
     * @return
     */
    @Transactional
    public void saveSelf(Orders order, HttpSession session) {
        //设置订单号
        Long orderId = IdWorker.getId();
        order.setNumber(String.valueOf(orderId));

        Long userId = (Long) session.getAttribute("user");

        //设置其他属性初始值
        order.setStatus(2);
        order.setUserId(userId);

        Long addressBookId = order.getAddressBookId();
        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getId,addressBookId);
        AddressBook addressBook = addressBookService.getOne(wrapper);
        if (addressBook == null)
            throw new CustomException("地址信息有误");
        order.setConsignee(addressBook.getConsignee());
        order.setAddress(addressBook.getProvinceName()==null?"":addressBook.getProvinceName()
                + (addressBook.getCityName() == null?"":addressBook.getCityName())
                + (addressBook.getDistrictName() == null?"":addressBook.getDistrictName())
                +(addressBook.getDetail() == null?"":addressBook.getDetail()));

        LambdaQueryWrapper<User> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(User::getId,userId);
        User user = userService.getOne(wrapper1);
        order.setUserName(user.getName());
        order.setPhone(user.getPhone());
        order.setOrderTime(LocalDateTime.now());
        order.setCheckoutTime(LocalDateTime.now());

        // 获取订单详细信息
        // 获取购物车中的数据
        LambdaQueryWrapper<ShoppingCart> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(wrapper2);
        // 获取总金额
        AtomicInteger amount = new AtomicInteger(0);
        List<OrderDetail> orderDetailList = shoppingCartList.stream().map(item -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(item, orderDetail, "id");
            orderDetail.setOrderId(orderId);
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        // 保存订单详细信息
        orderDetailService.saveBatch(orderDetailList);

        // 设置总金额amount
        order.setAmount(BigDecimal.valueOf(amount.intValue()));
        //保存到数据库
        this.save(order);

        // 添加成功 清空购物车
        shoppingCartService.remove(wrapper2);
    }
}
